package com.commerceE.util;

/**
 *=====================================================================
 * Property Utility 
 * 
 * Usage: 
 * 1. Check whether your property file path is in the "propertyLocations" array. If not, add it to the array. 
 * 2. Get the value according to the key, for instance: 
 *    String key = PropertyUtil.getValueByKey("key");
 *
 *---------------------------------------------------------------------
 * Update date  Contents
 *=====================================================================
 * 08/02/2011   create
 *
 */

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class PropertyUtil {
	private static Logger mLogger = Logger.getLogger(PropertyUtil.class.getName());
	private static Map<String, String> confMap = null;

	/** Specify configuration files location */
	private static String[] propertyLocations = { 
		Constant.APP_PROPERTITY_FILE 
		};

	/**
	 * Initialize the conMap when the getValueByKey() first time invoked.
	 */
	private static boolean init() {
		confMap = new HashMap<String, String>();
		for (String location : propertyLocations) {
			Properties dsProperties = new Properties();
			try {
				// load the properties
				InputStream pfis = PropertyUtil.class.getClassLoader()
						.getResourceAsStream(location);
				dsProperties.load(pfis);
				// traverse the properties, and put all the configurations into
				// Map
				for (Object key : dsProperties.keySet()) {
					confMap.put((String) key, (String) dsProperties.get(key));
				}
				
			} catch (FileNotFoundException fe) {
				mLogger.error("Initialize configuration failed. Can not find the property file : "
						+ location + ".  Error detail is " + fe.getMessage());
				return false;
			} catch (IOException ioe) {
				mLogger.error("Initialize configuration failed. "
						+ ioe.getMessage());
				return false;
			}
		}
		return true;
	}

	/**
	 * @param key
	 * @return Get the value according to the key. If no key-value matched, return null.
	 */
	public static String getValueByKey(String key) {
		if (confMap == null) {
			if ( !init() ) {
				return null;
			}
		}
		return confMap.get(key);
	}

}
